package timing.ukulele.third.handler;


import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.api.WxConsts;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.common.session.WxSessionManager;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutNewsMessage;
import me.chanjar.weixin.mp.builder.outxml.*;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.stereotype.Component;
import timing.ukulele.common.dictionary.YesOrNoEnum;
import timing.ukulele.third.constant.WxConstant;
import timing.ukulele.third.persistent.weixin.WxApp;
import timing.ukulele.third.persistent.weixin.WxAutoReply;
import timing.ukulele.third.persistent.weixin.WxMsg;
import timing.ukulele.third.persistent.weixin.WxUser;
import timing.ukulele.third.service.weixin.WxMsgService;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 微信消息
 */
@Slf4j
@Component
@AllArgsConstructor
public class MsgHandler extends AbstractHandler {

    @Override
    public WxMpXmlOutMessage handle(WxMpXmlMessage wxMpXmlMessage, Map<String, Object> map,
                                    WxMpService wxMpService, WxSessionManager wxSessionManager) throws WxErrorException {
        return null;
    }

    /**
     * 组装回复消息，并记录消息
     *
     * @param wxMessage
     * @param listWxAutoReply
     * @return
     */
    public static WxMpXmlOutMessage getWxMpXmlOutMessage(WxMpXmlMessage wxMessage, List<WxAutoReply> listWxAutoReply, WxApp wxApp, WxUser wxUser,
                                                         WxMsgService wxMsgService, SimpMessagingTemplate simpMessagingTemplate) {
        WxMpXmlOutMessage wxMpXmlOutMessage = null;
        // 记录接收消息
        WxMsg wxMsg = new WxMsg();
        wxMsg.setAppId(wxApp.getAppId());
        // TODO
        wxMsg.setWxUserId(wxUser.getId().toString());
        wxMsg.setAppName(wxApp.getName());
        wxMsg.setAppLogo(wxApp.getLogo());
        wxMsg.setNickName(wxUser.getNickName());
        wxMsg.setHeadImgUrl(wxUser.getHeadImgUrl());
        wxMsg.setType(WxConstant.WX_MSG_TYPE_1);
        wxMsg.setRepEvent(wxMessage.getEvent());
        wxMsg.setRepType(wxMessage.getMsgType());
        wxMsg.setRepMediaId(wxMessage.getMediaId());
        if (WxConsts.XmlMsgType.TEXT.equals(wxMessage.getMsgType())) {
            wxMsg.setRepContent(wxMessage.getContent());
        }
        if (WxConsts.XmlMsgType.VOICE.equals(wxMessage.getMsgType())) {
            wxMsg.setRepName(wxMessage.getMediaId() + "." + wxMessage.getFormat());
            wxMsg.setRepContent(wxMessage.getRecognition());
        }
        if (WxConsts.XmlMsgType.IMAGE.equals(wxMessage.getMsgType())) {
            wxMsg.setRepUrl(wxMessage.getPicUrl());
        }
        if (WxConsts.XmlMsgType.LINK.equals(wxMessage.getMsgType())) {
            wxMsg.setRepName(wxMessage.getTitle());
            wxMsg.setRepDesc(wxMessage.getDescription());
            wxMsg.setRepUrl(wxMessage.getUrl());
        }
        if (WxConsts.MediaFileType.FILE.equals(wxMessage.getMsgType())) {
            wxMsg.setRepName(wxMessage.getTitle());
            wxMsg.setRepDesc(wxMessage.getDescription());
        }
        if (WxConsts.XmlMsgType.VIDEO.equals(wxMessage.getMsgType())) {
            wxMsg.setRepThumbMediaId(wxMessage.getThumbMediaId());
        }
        if (WxConsts.XmlMsgType.LOCATION.equals(wxMessage.getMsgType())) {
            wxMsg.setRepLocationX(wxMessage.getLocationX());
            wxMsg.setRepLocationY(wxMessage.getLocationY());
            wxMsg.setRepScale(wxMessage.getScale());
            wxMsg.setRepContent(wxMessage.getLabel());
        }
        wxMsg.setReadFlag(YesOrNoEnum.NO.getValue());
        LocalDateTime now = LocalDateTime.now();
        wxMsg.setCreateTime(now);
        wxMsgService.save(wxMsg);
        // 推送websocket
        String destination = WxConstant.WEBSOCKET_USER_DESTINATION_PREFIX + WxConstant.WEBSOCKET_WX_MSG + wxMsg.getWxUserId();
        try {
            // TODO simpMessagingTemplate.convertAndSend(destination , JSONUtil.toJsonStr(wxMsg));
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (listWxAutoReply != null && listWxAutoReply.size() > 0) {
            WxAutoReply wxAutoReply = listWxAutoReply.get(0);
            // 记录回复消息
            wxMsg = new WxMsg();
            wxMsg.setAppId(wxApp.getAppId());
            wxMsg.setWxUserId(wxUser.getId().toString());
            wxMsg.setAppName(wxApp.getName());
            wxMsg.setAppLogo(wxApp.getLogo());
            wxMsg.setNickName(wxUser.getNickName());
            wxMsg.setHeadImgUrl(wxUser.getHeadImgUrl());
            wxMsg.setCreateTime(now.plusSeconds(1));
            wxMsg.setType(WxConstant.WX_MSG_TYPE_2);
            wxMsg.setRepType(wxAutoReply.getRepType());

            if (WxConsts.KefuMsgType.TEXT.equals(wxAutoReply.getRepType())) {
                wxMsg.setRepContent(wxAutoReply.getRepContent());
                wxMpXmlOutMessage = new TextBuilder().fromUser(wxMessage.getToUser()).toUser(wxMessage.getFromUser()).content(wxAutoReply.getRepContent()).build();
            }
            if (WxConsts.KefuMsgType.IMAGE.equals(wxAutoReply.getRepType())) {
                wxMsg.setRepName(wxAutoReply.getRepName());
                wxMsg.setRepUrl(wxAutoReply.getRepUrl());
                wxMsg.setRepMediaId(wxAutoReply.getRepMediaId());
                wxMpXmlOutMessage = new ImageBuilder().fromUser(wxMessage.getToUser()).toUser(wxMessage.getFromUser()).mediaId(wxAutoReply.getRepMediaId()).build();
            }
            if (WxConsts.KefuMsgType.VOICE.equals(wxAutoReply.getRepType())) {
                wxMsg.setRepName(wxAutoReply.getRepName());
                wxMsg.setRepUrl(wxAutoReply.getRepUrl());
                wxMsg.setRepMediaId(wxAutoReply.getRepMediaId());
                wxMpXmlOutMessage = new VoiceBuilder().fromUser(wxMessage.getToUser()).toUser(wxMessage.getFromUser()).mediaId(wxAutoReply.getRepMediaId()).build();
            }
            if (WxConsts.KefuMsgType.VIDEO.equals(wxAutoReply.getRepType())) {
                wxMsg.setRepName(wxAutoReply.getRepName());
                wxMsg.setRepDesc(wxAutoReply.getRepDesc());
                wxMsg.setRepUrl(wxAutoReply.getRepUrl());
                wxMsg.setRepMediaId(wxAutoReply.getRepMediaId());
                wxMpXmlOutMessage = new VideoBuilder().fromUser(wxMessage.getToUser()).toUser(wxMessage.getFromUser()).mediaId(wxAutoReply.getRepMediaId())
                        .title(wxAutoReply.getRepName()).description(wxAutoReply.getRepDesc()).build();
            }
            if (WxConsts.KefuMsgType.MUSIC.equals(wxAutoReply.getRepType())) {
                wxMsg.setRepName(wxAutoReply.getRepName());
                wxMsg.setRepDesc(wxAutoReply.getRepDesc());
                wxMsg.setRepUrl(wxAutoReply.getRepUrl());
                wxMsg.setRepHqUrl(wxAutoReply.getRepHqUrl());
                wxMsg.setRepThumbMediaId(wxAutoReply.getRepThumbMediaId());
                wxMsg.setRepThumbUrl(wxAutoReply.getRepThumbUrl());
                wxMpXmlOutMessage = new MusicBuilder().fromUser(wxMessage.getToUser()).toUser(wxMessage.getFromUser())
                        .thumbMediaId(wxAutoReply.getRepThumbMediaId())
                        .title(wxAutoReply.getRepName()).description(wxAutoReply.getRepDesc())
                        .musicUrl(wxAutoReply.getRepUrl()).hqMusicUrl(wxAutoReply.getRepHqUrl()).build();
            }
            if (WxConsts.KefuMsgType.NEWS.equals(wxAutoReply.getRepType())) {
                List<WxMpXmlOutNewsMessage.Item> list = new ArrayList<>();
                JSONObject content = JSON.to(JSONObject.class, wxAutoReply.getContent());//JSONUtil.parseObj(wxAutoReply.getContent());
                List<JSONObject> listJSONObject = content.getJSONArray("articles").toList(JSONObject.class);
                WxMpXmlOutNewsMessage.Item t;
                for (JSONObject jSONObject : listJSONObject) {
                    t = new WxMpXmlOutNewsMessage.Item();
//                    t.setTitle(jSONObject.getStr("title"));
//                    t.setDescription(jSONObject.getStr("digest"));
//                    t.setPicUrl(jSONObject.getStr("thumbUrl"));
//                    t.setUrl(jSONObject.getStr("url"));
                    t.setTitle(jSONObject.getString("title"));
                    t.setDescription(jSONObject.getString("digest"));
                    t.setPicUrl(jSONObject.getString("thumbUrl"));
                    t.setUrl(jSONObject.getString("url"));
                    list.add(t);
                }
                wxMsg.setRepName(wxAutoReply.getRepName());
                wxMsg.setRepDesc(wxAutoReply.getRepDesc());
                wxMsg.setRepUrl(wxAutoReply.getRepUrl());
                wxMsg.setRepMediaId(wxAutoReply.getRepMediaId());
                wxMsg.setContent(wxAutoReply.getContent());
                wxMpXmlOutMessage = new NewsBuilder().fromUser(wxMessage.getToUser()).toUser(wxMessage.getFromUser()).articles(list).build();
            }
            wxMsgService.save(wxMsg);
            try {
                // TODO simpMessagingTemplate.convertAndSend(destination , JSONUtil.toJsonStr(wxMsg));
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return wxMpXmlOutMessage;
    }

}
